use std::sync::{mpsc, Arc, Mutex};
use std::sync::atomic::{AtomicIsize, Ordering};
use std::thread;
use std::time::Instant;
use log::info;

pub fn mutex_test() {
    let num_mutex = Arc::new(Mutex::new(0));
    let mut list = Vec::new();

    let start = Instant::now();

    for _ in 0..5 {
        let num_mutex = num_mutex.clone();
        let thread = thread::spawn(move || {
            for _ in 0..200 {
                let mut num = num_mutex.lock().unwrap();
                *num += 1;
            }
        });
        list.push(thread);
    }

    for thread in list {
        thread.join().unwrap();
    }

    let result = *num_mutex.lock().unwrap();
    let duration = start.elapsed();

    info!("mutex_test执行时间: {:?}, result: {}", duration, result);
}

pub fn atomic_isize_test() {
    let atomic_size = Arc::new(AtomicIsize::new(0));
    let mut list = Vec::new();

    let start = Instant::now();

    for _ in 0..5 {
        let num_mutex = atomic_size.clone();
        let thread = thread::spawn(move || {
            for _ in 0..200 {
                num_mutex.fetch_add(1, Ordering::Relaxed);
            }
        });
        list.push(thread);
    }

    for thread in list {
        thread.join().unwrap();
    }

    let result = atomic_size.load(Ordering::Relaxed);
    let duration = start.elapsed();


    info!("atomic_isize_test执行时间: {:?}, total: {}", duration, result);
}

pub fn mpsc_test() {
    let (sender, receiver) = mpsc::channel();

    let start = Instant::now();

    for _ in 0..4 {
        let sender_clone = sender.clone();
        let thread = thread::spawn(move || {
            for _ in 0..250 {
                sender_clone.send(1).unwrap();
            }
        });
    }

    drop(sender);
    let mut result = 0;
    for rr in receiver.iter() {
        result += 1;
    }

    let duration = start.elapsed();

    info!("mpsc_test执行时间: {:?}, total: {} ", duration, result);
}